const MD5Utils = require('./encryption.js'); //加密模块引入
const checkUtils = require('./formatCheckUtils.js'); //格式校验模块引入
const config = require('../config.js') //全局配置文件

/**
 * 获取公共参数方法
 * url 请求url
 * parameter 私有参数
 */
function getCommonParameter(url, parameter) {
  //根据域名获取公共参数
  let commonParameters = {}
  commonParameters.output = 'json'
  commonParameters.callback = 'cb'
  commonParameters.key = config.txKey
  //公共参数和私有参数对象合并
  commonParameters = Object.assign({}, commonParameters, parameter)

  return encodeURI(getSign(url, commonParameters))
}

//验签方法
function getSign(path,obj) {
  var tmp = path;
  var tmpJson = {};
  //排序
  Object.keys(obj).sort().forEach(function (k) { tmpJson[k] = obj[k] });
  for (var item in tmpJson) {
    var jValue = tmpJson[item];//key所对应的value
    tmp = tmp + item + "=" + jValue + "&";
  } 
  tmp = tmp.substring(tmp,tmp.length - 1);
  tmp = tmp + '&sig=' + MD5Utils.md5(tmp + config.txSecurityKey)
  return tmp;
}

module.exports = { getCommonParameter }